package xml;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import arbori.Nod;
import functiiElementare.Constanta;

/**
 * 
 * @author Feri
 * @version 1.0
 */
/**
 * This program is saving the functional tree to a .xml file
 */
public class SaveXML {
	protected FileWriter fstream;
	protected BufferedWriter out;
	/**
	 * 
	 * @param a The root node
	 * @param fisier The file where the tree will be saved
	 */
	public SaveXML(Nod a, String fisier) throws IOException{
		fstream = new FileWriter(fisier);
		out = new BufferedWriter(fstream);
		out.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n");
		save(a,1);
		out.close();
	}
	public void save(Nod a, int nivel) throws IOException {
		// TODO Auto-generated method stub
		int i;
		for (i=1; i<=nivel; i++){
			out.write(" ");
			int index = (a.getClass().getName().lastIndexOf('.'));
			String fin = a.getClass().getName().substring(index + 1);
			if (fin.equals("Constanta"))
				out.write("<"+fin+"id=\""+nivel+"\" val=\"" + ((Constanta)a).getCt() + "\">\n");
			else
				out.write("<"+fin+"id=\""+nivel+"\">\n");
			if (a.getfStang() != null)
				save(a.getfStang(), nivel+1);
			if (a.getfDrept() != null)
				save(a.getfDrept(), nivel+1);
			for (i=1; i<=nivel; i++)
				out.write(" ");
			out.write("</"+fin+">"+"\n");
		}
	}
}
/*
 *T1:
 *Diag de clasa pt:
 *Sablon de proiectare conform principiului compunerii recursive: COMPOSITE
 *Singleton pt a asigura ca orice document XML are un nod radacina
 *
 * T2
 * un tag poate contine unul sau mai multe atribute
 * 
*/